const puppeteer = require('puppeteer');

(async () => {
  // 启动浏览器
  const browser = await puppeteer.launch({
    headless: false, // 设置为false以便观察页面加载过程
    devtools: true   // 打开开发者工具
  });
  
  // 创建新页面
  const page = await browser.newPage();
  
  // 监听网络请求
  page.on('request', request => {
    if (request.url().includes('.m3u8')) {
      console.log('发现M3U8请求:', request.url());
    }
  });
  
  page.on('response', response => {
    const url = response.url();
    if (url.includes('.m3u8')) {
      console.log('发现M3U8响应:', url);
      response.text().then(content => {
        console.log('M3U8内容预览:');
        console.log(content.substring(0, 500) + '...');
      }).catch(err => {
        console.log('无法获取M3U8内容:', err);
      });
    }
  });
  
  // 监听控制台消息
  page.on('console', msg => {
    if (msg.text().includes('hls') || msg.text().includes('HLS')) {
      console.log('控制台HLS相关消息:', msg.text());
    }
  });
  
  // 导航到目标页面
  console.log('正在加载页面...');
  await page.goto('https://time.geekbang.org/course/detail/100023501-81418', {
    waitUntil: 'networkidle2',
    timeout: 60000
  });
  
  // 等待页面加载完成
  await page.waitForTimeout(5000);
  
  // 分析页面中的视频元素
  console.log('分析页面中的视频元素...');
  const videoElements = await page.evaluate(() => {
    const videos = [];
    const videoTags = document.querySelectorAll('video');
    
    videoTags.forEach((video, index) => {
      videos.push({
        index: index,
        src: video.src,
        sources: Array.from(video.querySelectorAll('source')).map(s => ({
          src: s.src,
          type: s.type
        })),
        attributes: {
          autoplay: video.autoplay,
          controls: video.controls,
          loop: video.loop
        }
      });
    });
    
    return videos;
  });
  
  console.log('发现的视频元素:', videoElements);
  
  // 查找页面中的HLS相关JavaScript库
  console.log('检查HLS相关库...');
  const hlsLibraries = await page.evaluate(() => {
    const libraries = [];
    
    if (window.Hls) {
      libraries.push('hls.js');
    }
    
    if (window.VideoJS) {
      libraries.push('Video.js');
    }
    
    if (window.Clappr) {
      libraries.push('Clappr');
    }
    
    // 检查是否有其他可能的HLS实现
    const scripts = Array.from(document.querySelectorAll('script'));
    scripts.forEach(script => {
      if (script.src && (script.src.includes('hls') || script.src.includes('videojs'))) {
        libraries.push(`External script: ${script.src}`);
      }
    });
    
    return libraries;
  });
  
  console.log('发现的HLS相关库:', hlsLibraries);
  
  // 检查页面中的M3U8引用
  console.log('检查页面中的M3U8引用...');
  const m3u8Refs = await page.evaluate(() => {
    const refs = [];
    
    // 检查所有script标签
    const scripts = Array.from(document.querySelectorAll('script'));
    scripts.forEach(script => {
      if (script.textContent && script.textContent.includes('.m3u8')) {
        // 尝试提取URL
        const matches = script.textContent.match(/['"]([^'"]+\.m3u8[^'"]*)['"]/gi);
        if (matches) {
          refs.push(...matches.map(m => m.replace(/['"]/g, '')));
        }
      }
    });
    
    // 检查所有网络请求相关的变量
    const xhrElements = Array.from(document.querySelectorAll('[data-url*=".m3u8"], [src*=".m3u8"]'));
    xhrElements.forEach(el => {
      refs.push(el.getAttribute('data-url') || el.getAttribute('src'));
    });
    
    return refs.filter(Boolean);
  });
  
  console.log('发现的M3U8引用:', m3u8Refs);
  
  // 等待一段时间以捕获更多网络请求
  console.log('等待更多网络请求...');
  await page.waitForTimeout(10000);
  
  console.log('分析完成');
  
  // 不关闭浏览器，以便观察
  // await browser.close();
})();